from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config.settings import settings
import logging

logger = logging.getLogger(__name__)

# 构造数据库连接URL
try:
    SQLALCHEMY_DATABASE_URL = (
        f"mysql+pymysql://{settings.db_user}:{settings.db_password}"
        f"@{settings.db_host}:{settings.db_port}/{settings.db_name}"
    )
    logger.info(f"🔌 正在连接数据库: {SQLALCHEMY_DATABASE_URL}")
except AttributeError as e:
    logger.error("❌ 数据库配置缺失，请检查 .env 文件是否配置正确")
    raise

# 创建数据库引擎
try:
    engine = create_engine(
        SQLALCHEMY_DATABASE_URL,
        pool_pre_ping=True,  # 自动检测断开的连接
        echo=settings.db_echo_sql  # 是否打印SQL语句
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    Base = declarative_base()
except Exception as e:
    logger.error(f"❌ 数据库连接失败: {str(e)}")
    raise

# 添加 get_db 函数
def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()